package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.time.Duration;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SystemUserService systemUserService;

    @Override
    // 为了将key和value要么一起保存到redis中返回captchaVo，
    // 要么就不保存不返回captchaVo，所以要事务
    @Transactional
    public CaptchaVo getCaptcha() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        // 生成验证码文本
        String verCode = specCaptcha.text().toLowerCase();
        // 随机生成一个key
        String key = UUID.randomUUID().toString().replace("-", "");
        // 将验证码保存到redis中
        stringRedisTemplate.opsForValue().set(key,verCode, Duration.ofMinutes(1L));
        // 生成可以让浏览器识别的base64码
        String img = specCaptcha.toBase64();
        CaptchaVo captchaVo = new CaptchaVo(img,key);
        return captchaVo;
    }


    @Override
    public String login(LoginVo loginVo) {
        // 判断验证码是否正确
        String userCodeText = loginVo.getCaptchaCode().toLowerCase();
        String captchaKey = loginVo.getCaptchaKey();
        String trueCodeText = stringRedisTemplate.opsForValue().get(captchaKey);

        try {
            Assert.isTrue(userCodeText.equals(trueCodeText),"验证码错误");
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }

        // 正确后在redis删除验证码信息
        stringRedisTemplate.delete(captchaKey);


        // 判断用户是否存在以及密码是否正确
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        // 记得加密再做判断
        String userPassword = DigestUtils.md5Hex(password);
        QueryWrapper<SystemUser> systemUserQueryWrapper = new QueryWrapper<>();
        systemUserQueryWrapper.eq("username",username);
        SystemUser systemUser = systemUserService.getOne(systemUserQueryWrapper);
        Assert.notNull(systemUser,"用户不存在");
        Assert.isTrue(systemUser.getPassword().equals(userPassword),"密码错误");

        //生成 token
        String token = JwtUtil.createToken(systemUser.getId(),systemUser.getUsername());


        return token;
    }

    @Override
    public SystemUserInfoVo info(String token) {
        Claims claims = JwtUtil.parseToken(token);
        // 从claims中提取用户ID和用户名
        Long userId = claims.get("userId", Long.class);
        String username = claims.get("username", String.class);

        // 查询用户完整信息
        SystemUser systemUser = systemUserService.getById(userId);

        // 构造并返回SystemUserInfoVo对象
        SystemUserInfoVo userInfoVo = new SystemUserInfoVo();
        userInfoVo.setName(systemUser.getName());
        userInfoVo.setAvatarUrl(systemUser.getAvatarUrl());

        return userInfoVo;
    }
}
